package com.bw.wxy.mvp.view;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bw.wxy.R;
import com.bw.wxy.action.BroadAction;
import com.bw.wxy.common.Api;
import com.bw.wxy.common.SpUtils;
import com.bw.wxy.db.UserManager;
import com.bw.wxy.factroy.HttpCode;
import com.bw.wxy.mvp.base.view.BaseActivity;
import com.bw.wxy.mvp.contract.LoginContract;
import com.bw.wxy.mvp.di.DaggerLoginComponent;
import com.bw.wxy.mvp.di.LoginModules;
import com.bw.wxy.mvp.model.entity.BaseEntity;
import com.bw.wxy.mvp.model.entity.ResponseUserEntity;
import com.bw.wxy.mvp.model.entity.UploadEntity;
import com.bw.wxy.mvp.model.entity.UserEntity;
import com.bw.wxy.mvp.presenter.LoginPresenter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class DetailActivity extends BaseActivity<LoginPresenter> implements LoginContract.ILoginView, View.OnClickListener {
    private ImageView informationBack;
    private RelativeLayout rlImg;
    private ImageView detailHeadImg;
    private RelativeLayout rlName;
    private TextView detailName;
    private RelativeLayout rlSex;
    private TextView detailSex;
    private RelativeLayout detailBackParent;
    private View detailBackgroundBack;
    private TextView detailCamera;
    private TextView detailOpenPhoto;
    private TextView detailCancel;
    private String path=null;
    private View inflate;
    //    private View inflate_parent;
    private TextView editNick;
    private RelativeLayout detailBackParent2;
    private TextView detailPrivary;
    private TextView detailMan;
    private TextView detailWomen;
    private TextView detailCancel2;
    private List<UserEntity> userEntities;
    private int user_sex;
    private String user_sexs;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_img:
                detailBackParent.setVisibility(View.VISIBLE);
                Animation animation_img = AnimationUtils.loadAnimation(this, R.anim.tran);
                detailBackParent.startAnimation(animation_img);
                break;
            case R.id.rl_name:
                PopupWindow pop = new PopupWindow();
                pop.setContentView(inflate);
                pop.setOutsideTouchable(true);
                inflate.findViewById(R.id.nickname_save).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String nick = editNick.getText().toString().trim();
                        detailName.setText(nick);
                        pop.dismiss();
                    }
                });
                WindowManager.LayoutParams attributes = getWindow().getAttributes();
                attributes.alpha = 0.5f;
                getWindow().setAttributes(attributes);
                pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams attributes = getWindow().getAttributes();
                        attributes.alpha = 1f;
                        getWindow().setAttributes(attributes);
                    }
                });
                pop.setFocusable(true);
                pop.setWidth(1300);
                pop.setHeight(1500);
                pop.showAsDropDown(rlName, 60, 0);
                break;
            case R.id.rl_sex:
                detailBackParent2.setVisibility(View.VISIBLE);
                Animation animation_sex = AnimationUtils.loadAnimation(this, R.anim.tran);
                detailBackParent2.startAnimation(animation_sex);
                break;
            case R.id.detail_camera:
                openCamera();
                break;
            case R.id.detail_open_photo:
                openPhoto();
                break;
            case R.id.detail_cancel:
                detailBackParent.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_privary:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("保密");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_man:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("男");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_women:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        detailSex.setText("女");
                    }
                });
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.detail_cancel2:
                detailBackParent2.setVisibility(View.INVISIBLE);
                break;
            case R.id.information_back:
                String name = detailName.getText().toString().trim();
                String sex = detailSex.getText().toString().trim();
                if (sex.equals("男")){
                    user_sex=0;
                }else if (sex.equals("女")){
                    user_sex=1;
                }
                if (path!=null){
                    p.uploadhead(path,HttpCode.UPLOADIMGCODE);
                }
                p.updateUser(name,user_sex,path,HttpCode.UPDATEUSERCODE);
                List<UserEntity> userEntities = UserManager.getInstance().getDaoSession().loadAll(UserEntity.class);
                for (UserEntity userEntity : userEntities) {
                    if (path!=null){
                        userEntity.setUser_img(path);
                    }
                    userEntity.setUser_name(name);
                    userEntity.setUser_sex(user_sex+"");
                    UserManager.getInstance().getDaoSession().update(userEntity);
                }
                EventBus.getDefault().postSticky("刷新");
                finish();
                break;
        }
    }

    private File file;
    private Uri uri;
    private void openCamera(){
        String name = ""+System.currentTimeMillis();
        file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath(),name+".jpg");
        //判断SDK版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            //SDK版本大于10->兼容处理沙箱机制
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DISPLAY_NAME,name);
            values.put(MediaStore.Images.Media.RELATIVE_PATH,"Pictures");
            values.put(MediaStore.Images.Media.MIME_TYPE,"image/JPEG");
            uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            //7-9
            uri = FileProvider.getUriForFile(this,"com.bw.wxy",file);
        }else {
            //低版本
            uri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(intent,102);

    }

    private void openPhoto(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,101);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode!=RESULT_OK){
            detailBackParent.setVisibility(View.INVISIBLE);
            return;
        }
        //根据requestCode区分图库或相机
        if (101 == requestCode){
            Cursor cursor =  getContentResolver().query(data.getData(),new String[]{MediaStore.Images.Media.DATA},
                    null,null,null);
            path = null;
            while (cursor.moveToNext()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
            Glide.with(this).load(path)
                    .transform(new CenterCrop(),new CircleCrop())
                    .into(detailHeadImg);
            detailBackParent.setVisibility(View.INVISIBLE);
        }
        if (102 == requestCode){
            path = null;
            path = file.getAbsolutePath();
            Glide.with(this).load(path)
                    .transform(new CenterCrop(),new CircleCrop())
                    .into(detailHeadImg);
            detailBackParent.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public int addBarColor() {
        return Color.WHITE;
    }

    @Override
    public View addStatusView() {
        return f(R.id.detail_linear);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_detail;
    }

    @Override
    public void initView() {
        inflate = LayoutInflater.from(getApplicationContext()).inflate(R.layout.view_detail_pop, null);
        editNick = inflate.findViewById(R.id.edit_nickname);
        informationBack = findViewById(R.id.information_back);
        informationBack.setOnClickListener(this::onClick);
        rlImg = findViewById(R.id.rl_img);
        rlImg.setOnClickListener(this::onClick);
        detailHeadImg = findViewById(R.id.detail_head_img);
        rlName = findViewById(R.id.rl_name);
        rlName.setOnClickListener(this::onClick);
        detailName = findViewById(R.id.detail_name);
        rlSex = findViewById(R.id.rl_sex);
        rlSex.setOnClickListener(this::onClick);
        detailSex = findViewById(R.id.detail_sex);
        detailBackParent = findViewById(R.id.detail_back_parent);
        detailBackgroundBack = findViewById(R.id.detail_background_back);
        detailCamera = findViewById(R.id.detail_camera);
        detailOpenPhoto = findViewById(R.id.detail_open_photo);
        detailCancel = findViewById(R.id.detail_cancel);
        detailCamera.setOnClickListener(this::onClick);
        detailOpenPhoto.setOnClickListener(this::onClick);
        detailCancel.setOnClickListener(this::onClick);
        detailBackParent2 = findViewById(R.id.detail_back_parent2);
        detailPrivary = findViewById(R.id.detail_privary);
        detailMan = findViewById(R.id.detail_man);
        detailWomen = findViewById(R.id.detail_women);
        detailCancel2 = findViewById(R.id.detail_cancel2);
        detailPrivary.setOnClickListener(this::onClick);
        detailMan.setOnClickListener(this::onClick);
        detailWomen.setOnClickListener(this::onClick);
        detailCancel2.setOnClickListener(this::onClick);
        userEntities = UserManager.getInstance().getDaoSession().loadAll(UserEntity.class);
        LogUtils.json(userEntities);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (userEntities.get(0).getUser_img()!=null){
                    Glide.with(getApplicationContext()).load(userEntities.get(0).getUser_img())
                            .transform(new CenterCrop(), new CircleCrop())
                            .into(detailHeadImg);
                }else {
                    detailHeadImg.setImageResource(R.mipmap.pn_placeholder);
                }
                detailName.setText(userEntities.get(0).user_name);
                if (userEntities.get(0).user_sex.equals("0")){
                    user_sexs="男";
                }else {
                    user_sexs="女";
                }
                detailSex.setText(user_sexs);
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void inject() {
        DaggerLoginComponent.builder().loginModules(new LoginModules(this)).build().updateuser(this);
    }

    @Override
    public void showView(BaseEntity baseEntity) {

    }

    @Override
    public void showHeadImg(BaseEntity baseEntity) {
        if (baseEntity instanceof UploadEntity){
            UploadEntity baseEntity1 = (UploadEntity) baseEntity;
            if (baseEntity1.getStatuesCode().equals("200")){
                Toast.makeText(this, "头像"+baseEntity1.getMsg(), Toast.LENGTH_SHORT).show();
                EventBus.getDefault().postSticky("刷新");
            }
        }
    }



}